<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-11-19
 * Time: 11:13
 */

namespace app\common\model\traits;

use app\admin\model\ShopExpressCompany;
use app\api\model\mp\v1\OrderSubscribeMessage;
use app\common\enum\KuaiDi100WayBillStatus;
use app\common\enum\OrderEnum;
use app\common\exception\ParameterException;
use app\common\service\KuaiDi100;
use app\common\validate\Order as Validate;
use think\facade\Queue;

trait HandleOrderExpress
{
    /**
     * 对订单进行发货操作
     * @param $data
     * @return bool
     */
    public static function deliveryShopOrder($data)
    {
        $validate = new Validate();
        if (!$validate->scene('delivery_order')->check($data)) {
            throw new ParameterException([
                'msg' => $validate->getError(),
            ]);
        }

        // 先通过id查找该订单是否已经发过货了，如果已经有发过货则进行更新操作
        $order = static::with(['express' => function($query) {
            $query->field(['id,express_company_id,order_id,express_no']);
        },'user','address' => function($query) {
            $query->field('id, tel_number');
        }])
            ->where([['id','=',$data['id']]])
            ->field('id,order_no,title,user_id,address_id,allow_delivery_subscribe,status,delivery_time')
            ->find();
        if (empty($order)) {
            return false;
        }

        // 更新订单发货时间
        $order->allowField(['status','delivery_time'])
            ->save([
                'status' => OrderEnum::SHIP_ORDER,
                'delivery_time' => time()
            ]);
        $order->refresh();
        $order = $order->toArray();
        // 根据快递公司id获取快递公司信息
        $express_company = ShopExpressCompany::where([['id','=',$data['express_company_id']]])
            ->find()
            ->toArray();
        if (empty($order['express'])) {
            self::createExpressData($data['id'], [
                'express_company_id' => $data['express_company_id'],
                'express_no' => $data['express_no']
            ]);

            self::createReceiptsTimeoutQueue($order['delivery_time'],$order['order_no']);

            // 给用户发送发货通知
            if ($order['allow_delivery_subscribe'] == 1) {
                (new OrderSubscribeMessage())->sendOrderSubscribeMessage('delivery',$order['user']['openid'],[
                    'delivery_time' => $order['delivery_time'],
                    'order_no' => $order['order_no'],
                    'express_no' => $data['express_no'],
                    'express_company_name' => $express_company['name'],
                    'title' => $order['title']
                ]);
            }
        } else if ($order['express']['express_no'] != $data['express_no'] || $order['express']['express_company_id'] != $data['express_company_id']) {
            self::updateExpressData($data['id'], [
                'express_company_id' => $data['express_company_id'],
                'express_no' => $data['express_no']
            ]);
        }

        // 如果数据库的快递单号为空或者数据库中的快递单号跟提交的不一样，则重新订阅快递物流信息推送
//        if (empty($order['express']) || $order['express']['express_no'] != $data['express_no'] || $order['express']['express_company_id'] != $data['express_company_id']) {
//            (new KuaiDi100())->SubscriptMessagePushServer($express_company['code'],$data['express_no'],$order['address']['tel_number']);
//        }

        return true;
    }

    /**
     * 刷新订单快递物流信息
     * @param $id
     * @return array|integer
     */
    public static function refreshOrderExpressData($id)
    {
        $validate = new Validate();
        if (!$validate->scene('refresh_express')->check(['id' => $id])) {
            throw new ParameterException([
                'msg' => $validate->getError(),
            ]);
        }

        // 根据id获取订单的快递信息
        $order = static::with(['express' => function($query) {
            $query->with(['express_company'])
                ->field(['id,order_id,express_company_id,express_no']);
        },'address' => function($query) {
            $query->field('id, tel_number');
        }])
            ->where([['id','=',$id]])
            ->field('id,order_no,address_id,status')
            ->find();
        if (empty($order)) {
            return -1;
        }
        $order_data = $order->toArray();
        // 判断订单是否为已签收
        if ($order_data['status'] == OrderEnum::USER_SIGN_EXPRESS) {
            return -2;
        }
        // 更新订单物流信息
        try {
            $express_data = (new KuaiDi100())->realTimeQueriesExpress($order_data['express']['express_company']['code'], $order_data['express']['express_no'], $order_data['address']['tel_number']);

            $update_data = [
                'express_company_id' => $order_data['express']['express_company_id'],
                'express_no' => $order_data['express']['express_no'],
                'logistics_information' => $express_data['data'],
                'express_status' => $express_data['state']
            ];

            // 如果查询到订单的物流信息为已签收，则判断当前订单是否为用户签收快递状态，如果不是则更新订单状态和将加入超时自动确认收货
            if ($express_data['state'] == KuaiDi100WayBillStatus::SIGN && $order_data['status'] != OrderEnum::USER_SIGN_EXPRESS) {
                $order->allowField(['status'])
                    ->save([
                        'status' => OrderEnum::USER_SIGN_EXPRESS
                    ]);
            }

            // 更新数据库信息
            self::updateExpressData($order_data['id'],$update_data);

            return $update_data;

        } catch (\Exception $e) {
            return -1;
        }
    }

    /**
     * 创建订单快递信息
     * @param $order_id
     * @param $express_data
     */
    public static function createExpressData($order_id, $express_data)
    {
        // 查找对应的订单，然后通过关联新增的方法进行创建
        $order = static::find($order_id);
        // 如果还没有关联数据 则进行新增
        $order->express()->save([
            'express_company_id' => $express_data['express_company_id'],
            'express_no' => $express_data['express_no'],
            'logistics_information' => $express_data['logistics_information'] ?? [],
            'express_status' => $express_data['express_status'] ?? -1
        ]);
    }

    /**
     * 更新订单快递信息
     * @param $order_id
     * @param $express_data
     */
    public static function updateExpressData($order_id, $express_data)
    {
        // 查找对应的订单，然后通过关联更新的方法进行更新
        $order = static::find($order_id);
        // 对数据进行关联更新
        $order->express->save([
            'express_company_id' => $express_data['express_company_id'],
            'express_no' => $express_data['express_no'],
            'logistics_information' => $express_data['logistics_information'] ?? [],
            'express_status' => $express_data['express_status'] ?? -1
        ]);
    }

    /**
     * 创建超时自动确认收货队列
     * @param $sign_time
     * @param $order_no
     */
    public static function createReceiptsTimeoutQueue($sign_time,$order_no)
    {
        // 判断收货时间到现在已经过去了多长时间，然后计算出自动确认收货的时间
        $sign_time_stamp = $sign_time;
        if (is_string($sign_time)) {
            $sign_time_stamp = strtotime($sign_time);
        }
        $receipts_timeout_time = 1209600 - (time() - $sign_time_stamp);
//        $receipts_timeout_time = 60 - (time() - $sign_time_stamp);
//        Queue::later($receipts_timeout_time, 'app\common\job\OrderReceiptsTimeoutHandleQueue', [
//            'order_no' => $order_no
//        ], 'order_receipts_timeout_handle_queue');
    }
}